﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.Common;
using Microsoft.VisualStudio.TestTools.Exceptions;
using Microsoft.VisualStudio.TestTools.Vsip;
using TLM.PlaylistGenerator.Model;
using TLM.VsmdiReader;

namespace TLM.PlaylistGenerator
{
    /// <summary>
    /// Extension methods for TestList class
    /// </summary>
    public static class TestListExtensions
    {
        /// <summary>
        /// Converts test lists to playlist
        /// </summary>
        /// <param name="testList">The test list to be converted</param>
        /// <param name="tmiInstance">The tmi instance that can be used to resolve the fully qualified names for a given test. Usualy provided by visual studio</param>
        /// <param name="testsNotFound">Ref parameter that countains the number of tests that could not be found</param>
        /// <returns>Aplaylist which represents this node</returns>
        /// <exception cref="System.ArgumentNullException">
        /// testList
        /// or
        /// tmiInstance
        /// </exception>
        public static Playlist ConvertToPlaylist(this TestList testList, ITmi tmiInstance, ref int testsNotFound)
        {
            if (testList == null)
            {
                throw new ArgumentNullException("testList");
            }

            if (tmiInstance == null)
            {
                throw new ArgumentNullException("tmiInstance");
            }

            Playlist playlist = new Playlist();

            foreach (TestLink testLink in testList.GetAllTestLinks())
            {
                if (testLink.Enabled)
                {
                    try
                    {
                        // Retrieve the FQN using the TMI. The TMI can get us the test by ID. The HumanReadableId is the FQN of the test.
                        string fullyQualifiedName = tmiInstance.GetTest(new TestId(testLink.Id)).HumanReadableId;

                        // Add the test to the playlist
                        playlist.IncludedTests.Add(new IncludedTest(fullyQualifiedName));
                    }
                    catch (IdNotFoundException)
                    {
                        // TestId could not be found, handle this exception so the migration won't crash
                        testsNotFound++;
                    }
                }
            }

            return playlist;
        }
    }
}
